import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {ServerConfigService} from './server-config.service';

@Injectable()
export class ApiService {

  baseUrl: string;
  baseWebSocketUrl: string;
  urls: {
    [name: string]: any;
    paginationUrl?: string;
  };

  constructor(
    public http: HttpClient,
  ) {
  }

  configObserver(): Observable<any> {
    return new Observable<any>((observe) => {
      observe.next({
        baseUrl: this.baseUrl,
      });
    });
  }

  get(url: string, options: { observe: any; [p: string]: any } = {observe: 'response'}): Observable<any> {
    return new Observable<any>((observe) => {
      this.configObserver().subscribe((config) => {
        this.http.get(config.baseUrl + url, options).subscribe({
          next: (resp) => {
            observe.next(resp);
          },
          error: (error) => {
            observe.error(error);
          },
          complete: () => {
            observe.complete();
          }
        });
      });
    });
  }

  post(url: string, data: any, options: { observe: any; [p: string]: any } = {observe: 'response'}): Observable<any> {
    return new Observable<any>((observe) => {
      this.configObserver().subscribe((config) => {
        this.http.post(config.baseUrl + url, data, options).subscribe({
          next: (resp) => {
            observe.next(resp);
          },
          error: (error) => {
            observe.error(error);
          },
          complete: () => {
            observe.complete();
          }
        });
      });
    });
  }

  put(url: string, data: any, options: { observe: any; [p: string]: any } = {observe: 'response'}): Observable<any> {
    return new Observable<any>((observe) => {
      this.configObserver().subscribe((config) => {
        this.http.put(config.baseUrl + url, data, options).subscribe({
          next: (resp) => {
            observe.next(resp);
          },
          error: (error) => {
            observe.error(error);
          },
          complete: () => {
            observe.complete();
          }
        });
      });
    });
  }

  delete(url: string, options: { observe: any; [p: string]: any } = {observe: 'response'}): Observable<any> {
    return new Observable<any>((observe) => {
      this.configObserver().subscribe((config) => {
        this.http.delete(config.baseUrl + url, options).subscribe({
          next: (resp) => {
            observe.next(resp);
          },
          error: (error) => {
            observe.error(error);
          },
          complete: () => {
            observe.complete();
          }
        });
      });
    });
  }
}

